package com.common.base.base

import android.app.Application
import android.content.Intent
import android.content.res.Resources
import android.os.Bundle
import android.os.Process
import com.common.base.http.exceptions.CrashHandler
import com.common.base.http.main.ApiConfig
import com.common.base.tools.utils.Logs
import com.common.base.tools.utils.file.FileUtil
import com.common.base.tools.utils.file.StorageEnum
import com.didi.drouter.api.DRouter
import com.tencent.mmkv.BuildConfig
import com.tencent.mmkv.MMKV

abstract class BaseApplication : Application() {
    private var mStartActivityTime: Long = 0


    /**
     * 不输出指定的Url路径的日志 不能包含，一般用来过滤心跳日志，比较拉的后端,一般不用
     * @return
     */
    val filterUrlLogList: MutableList<String>
        get() = ArrayList()

    /**
     * 不输出指定的糟乱的日志(内容) 部分相 ，一般用来过滤息屏的socket失败日志，一般不用
     * @return
     */
    val filterLogMsg: MutableList<String>
        get() = ArrayList()

    override fun onCreate() {
        super.onCreate()
        application = this
        initDRouter()
        initConfig()
        init()
    }

    private fun init() {
        ApiConfig.filterUrlLogList = filterUrlLogList
        ApiConfig.filterLogMsg = filterLogMsg
        MMKV.initialize(
            this,
            FileUtil.getStorePath(StorageEnum.STORAGE_DATA_FILES)
        )
    }

    override fun getResources(): Resources {
        val resources = super.getResources()
        if (resources != null && resources.configuration.fontScale != 1.0f) {
            val configuration = resources.configuration
            configuration.fontScale = 1.0f
            resources.updateConfiguration(configuration, resources.displayMetrics)
        }
        return resources
    }

    protected open fun initConfig() {
        Logs.initXLog()
        if (!BuildConfig.DEBUG) CrashHandler.instance.init() //application 中初始化
    }

    protected fun destroySDK() {}
    override fun onTerminate() {
        super.onTerminate()
        destroySDK()
    }

    override fun startActivity(intent: Intent, options: Bundle?) {
        if (System.currentTimeMillis() - mStartActivityTime > 500) {
            mStartActivityTime = System.currentTimeMillis()
            super.startActivity(intent, options)
        }
    }

    private fun initDRouter() {
        DRouter.init(application);
        if (BuildConfig.DEBUG) {   // 这两行必须写在init之前，否则这些配置在init过程中将无效

        }
    }

    fun exitApp() {
        Process.killProcess(Process.myPid())
        System.exit(1)
    }

    companion object {
        var application: BaseApplication? = null
            private set
    }
}